package com.taocyb.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;

import com.taocyb.commons.uc.entity.User;
import com.taocyb.commons.uc.service.UserService;
import com.taocyb.framework.utils.SecurityUtils;
import com.taocyb.framework.utils.Servlets;

public abstract class BaseLoginController {
	
	@Autowired
	protected UserService userService;
	
	/**
	 * 获取登陆用户信息
	 */
	protected User getLoginUser(HttpServletRequest request){
		Cookie cookie = Servlets.getCookie(request, "_uid");
		if(cookie != null){
			String cookieValue = new String(Base64.decodeBase64(cookie.getValue()));
			String[] values = cookieValue.split(":");
			if(values.length == 3){
				String cookieLoginName = values[0];
				long cookieValidTime = Long.parseLong(values[1]);
				String cookieMd5Value = values[2];
				
				if(cookieValidTime > System.currentTimeMillis()){
					User user = userService.findUserByLoginName(cookieLoginName);
					String md5Value = SecurityUtils.encryptCookieValueMd5(user.getLoginName(), user.getPassword());
					if(md5Value.equals(cookieMd5Value)){
						return user;
					}
				}
			}
		}
		
		return null;
	}
}
